<template>
  <div class="full-height bg-white padding-20 flex column no-wrap">
    <div>
      <div class="title">重启任务信息</div>
      <div class="flex margin-t-20 justify-between">
        <div>开始时间：{{ data.startDate || '--' }}</div>
        <div>执行周期：{{ cycleObj[data.exeCycle] || '--' }}</div>
        <div>有效期至：{{ data.valiDate || '--'}}</div>
      </div>
      <div class="margin-t-15">
        任务说明：{{ data.remark || '--' }}
      </div>
    </div>
    <div class="divider"></div>
    <div class="margin-t-15">
      <yz-condition-filter
        v-model="params"
        @resetSearch="resetSearch"
        @onSubmit="onSubmit"
        class="filter"
      >
        <fuzzy-search
          v-model.trim="params.gateway"
          :isShowValue="false"
          showAllOption
          isFilter
          smallSize
          filterByFe
          title="网关序列号"
          :options="gatewayOptions"
          class="margin-r-20"
        ></fuzzy-search>
        <yz-input v-model="params.status"
                  inputType="select"
                  :options="execStatusList"
                  title="执行结果"
                  class="margin-r-20"
        >
        </yz-input>
      </yz-condition-filter>
    </div>
    <q-tabs
      v-if="times && times.length > 1"
      v-model="tab"
      narrow-indicator
      inline-label
      dense
      align="left"
      indicator-color="primary"
      active-color="primary"
      class="tab-label margin-b-10"
    >
      <q-tab v-for="(item, index) in times" :key="index" :name="item.value" :label="item.label"/>
    </q-tabs>
    <div class="flex-1 padding-t-10 padding-b-10" style="height: 0">
      <q-table
        :data="tableData"
        :columns="columns"
        row-key="prodId"
        class="scroll stick-last-col full-height"
        :loading="tableLoading"
        :pagination="pagination"
        hide-bottom
        separator="cell"
        no-data-label="暂无数据"
        color="primary"
      >
        <template v-slot:body-cell-operations="props">
          <q-td class="operations" style="width: 100px">
            <div class="btn-group text-center">
              <q-btn
                flat
                color="primary"
                class="table-flat-btn"
                :disable="!props.row.result || !isOnTime || props.row.result+'' ==='1'"
                @click="retryRestart(props.row)">
                重试
              </q-btn>
            </div>
          </q-td>
        </template>
      </q-table>
    </div>
  </div>
</template>

<script>
import { execStatusList, cycleObj, errorReasonObj } from '../components/constant'
import { getTaskDetail, retryRestart } from '../../../../boot/miot/task'
import moment from 'moment/moment'
import { numberToChinese } from '../../../../assets/js/util'

export default {
  name: 'task-detail',
  components: {
  },
  data () {
    return {
      id: '',
      execStatusList: execStatusList,
      cycleObj: cycleObj,
      tableLoading: false,
      tab: '1',
      columns: [
        { name: 'boxId', label: '网关序列号', align: 'left', field: 'boxId' },
        { name: 'startTime', label: '最后执行时间', align: 'left', field: 'startTime' },
        { name: 'status', label: '执行结果', align: 'left', field: 'status' },
        { name: 'errorTimes', label: '失败次数', align: 'left', field: 'errorTimes' },
        { name: 'errorReason', label: '最后失败原因', align: 'left', field: 'errorReason' },
        { name: 'operations', label: '操作', align: 'left', field: 'operations' }
      ],
      params: {
        gateway: '',
        status: ''
      },
      selParams: {
        gateway: '',
        status: ''
      },
      // 表格分页配置
      pagination: {
        // 总条数
        rowsNumber: 0
      },
      data: {}
    }
  },
  watch: {
    tab () {
      this.params.gateway = ''
      this.selParams.gateway = ''
    }
  },
  computed: {
    tableDataObj () {
      return this.data.timesTaskLogs || {}
    },
    tableDataAll () {
      const result = []
      Object.keys(this.tableDataObj).forEach(item => {
        const res = this.tableDataObj[item]
        res.forEach(column => {
          result.push({
            ...column,
            errorTimes: column.errorTimes || '--',
            errorReason: errorReasonObj[column.errorReason] || '--',
            startTime: column.startTime ? moment(column.startTime).format('YYYY-MM-DD HH:mm:ss') : '--',
            times: column.times ? column.times : Number(item),
            status: column.result ? column.result === 1 ? '成功' : '失败' : '--'
          })
        })
      })
      return result
    },
    times () {
      // 1. 过滤重复
      // 2. 排序
      // 3. 转成中文
      return Object.keys(this.tableDataObj).filter((value, index, self) => {
        return self.indexOf(value) === index
      }).sort((a, b) => Number(a) - Number(b)).map(item => ({ label: `第${numberToChinese(item)}次`, value: item }))
    },
    // 是否在有效期内
    isOnTime () {
      if (this.data.startDate && this.data.valiDate) {
        const now = new Date().getTime()
        return new Date(this.data.startDate).getTime() < now && now < new Date(this.data.valiDate).getTime()
      }
      return false
    },
    tableData () {
      return this.tableDataAll.filter(item => item.times === Number(this.tab)).filter(item => {
        if (this.selParams.gateway) {
          return item.boxId === this.selParams.gateway
        }
        return true
      }).filter(item => {
        if (this.selParams.status) {
          return item.result === Number(this.selParams.status)
        }
        return true
      })
    },
    gatewayOptions () {
      return this.tableData.map(item => ({
        label: item.boxId,
        value: item.boxId
      }))
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      const { id } = vm.$route.query
      vm.id = id
      vm.init()
    })
  },
  methods: {
    init () {
      this.data = {}
      this.tab = '1'
      Object.assign(this.params, this.$options.data().params)
      Object.assign(this.selParams, this.$options.data().selParams)
      this.getDetailData()
    },
    getDetailData () {
      this.tableLoading = true
      getTaskDetail(this.id).then(res => {
        const data = res.data
        data.startDate = moment(data.startDate).format('YYYY-MM-DD HH:mm:ss')
        data.valiDate = moment(data.valiDate).format('YYYY-MM-DD HH:mm:ss')
        this.data = data
      }).finally(() => {
        this.tableLoading = false
      })
    },
    // 查询
    onSubmit () {
      this.selParams.gateway = this.params.gateway
      this.selParams.status = this.params.status
    },
    // 重置
    resetSearch () {
      Object.assign(this.params, this.$options.data.call(this).params)
      Object.assign(this.selParams, this.$options.data.call(this).selParams)
    },
    // 重试
    retryRestart (row) {
      retryRestart(row.id).then(() => {
        this.$message.success('已重试')
        this.getDetailData()
      })
    }
  }
}
</script>

<style scoped lang="scss">
.title{
  font-size: 16px;
  color: #5f77fd;
}
.divider{
  width: 100%;
  height: 1px;
  background: #D3D3D3;
  margin: 8px 0
}
/deep/ .form-inline{
  padding: 0;
}
</style>
